require.config({
    paths: {
        jquery: 'jquery-2.1.1',
        bootstrap: 'bootstrap.min'
    },
    shim: {
        bootstrap: {
            deps: ['jquery'],
            exports: 'bootstrap'
        }
    }
});
require(['domready!'], function() {
    require(['jquery', 'bootstrap'], function($, bootstrap) {
        $('#refresh').click(function() {
            location.reload();
        });

        $('#search_submit').click(function() {
            $('#search_form').submit(function() {
                return false;
            });
            console.log($('#search_form').serialize());
            $.ajax({
                url: './models/interface.php?method=getMusic',
                method: 'post',
                data: $('#search_form').serialize(),
                dataType: 'json'
            }).done(function(data) {
                if (data.result === true) {
                    $('#search_form').hide();
                    var musics = data.musics;
                    $('#search').append($('<legend></legend>').append($('<h2></h2>').html('Download')));
                    for (var i = 0; i < musics.length; i++) {
                        var name = musics[i].singer + '-' + musics[i].song + '.mp3';
                        $('#search').append($('<div class="col-sm-offset-2 col-sm-offset-10"></div>').append($('<h3></h3>')
                                .append($('<a></a>').html((i + 1) + '. ' + name).attr({href: 'musics/' + name, download: name}))));
                    }
                }
            }).fail(function() {
                console.log('fail');
            });
        });

        $('#add_submit').click(function() {
            $('#add_form').submit(function() {
                return false;
            });
            var fd = new FormData(document.getElementById('add_form'));
            $.ajax({
                url: './models/interface.php?method=addMusic',
                method: 'post',
                data: fd,
                processData: false,
                contentType: false
            }).done(function() {
                alert('Add Success');
            });
        });

        $('#delete_submit').click(function() {
            $('#delete_form').submit(function() {
                return false;
            });
            $.ajax({
                url: './models/interface.php?method=deleteMusic',
                method: 'post',
                dataType: 'json',
                data: $('#delete_form').serialize()
            }).done(function(data) {
                document.write(data);
            }).fail(function() {
                console.log('fail');
            })
        });
    })
})